package com.cube.truthseer.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cube.truthseer.common.entity.enums.ResultCode;
import com.cube.truthseer.common.entity.vo.ResultMessage;
import com.cube.truthseer.common.exception.BadRequestException;
import com.cube.truthseer.common.minio.MinIOUtil;
import com.cube.truthseer.common.security.AuthUser;
import com.cube.truthseer.common.security.context.UserContext;
import com.cube.truthseer.common.security.token.TokenUtil;
import com.cube.truthseer.common.utils.ResultUtil;
import com.cube.truthseer.common.utils.StringUtil;
import com.cube.truthseer.common.utils.UserRequest;
import com.cube.truthseer.entity.picture.enums.PictureDeleteStatus;
import com.cube.truthseer.entity.picture.enums.PictureVisableStatus;
import com.cube.truthseer.entity.picture.po.Picture;
import com.cube.truthseer.mapper.PictureMapper;
import com.cube.truthseer.service.IPictureService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static com.cube.truthseer.common.entity.constants.ErrorInfo.Msg.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zw
 * @since 2024-03-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements IPictureService {

    private final MinIOUtil minIOUtil;
    private final TokenUtil tokenUtil;
//上传图片
    @Transactional
    @Override
    public ResultMessage<String> insertPicture(MultipartFile multipartFile) {
        log.info("mul:{}",multipartFile);
        String token = UserRequest.getCurrentToken();
        log.info("token:"+token);
        AuthUser authUser = tokenUtil.parseToken(token);
        log.info("authUser:{}",authUser);
        String userId =String.valueOf( authUser.getId());
        //1.判断用户是否登录
        if(userId==null|| StringUtil.isBlank(userId)){
            throw new BadRequestException(OPERATE_FAILED);
        }
        //2.判断是否上传了图片
        if(multipartFile==null||multipartFile.getSize()==0){
            throw  new BadRequestException(REQUEST_PARAM_ILLEGAL);
        }
        String prefix=userId;
        //3.放入minio
        String  locate = minIOUtil.uploadImgFile(userId, prefix, multipartFile, null);
        log.info("上传图片到Minio中，图片路径是{}",locate);
        //4.构建图片上传
        Picture picture=new Picture();//创建对象
        picture.setUserId(Long.valueOf(userId));
        picture.setPicturePath(locate);//minio路径
        picture.setIsDelete(PictureDeleteStatus.NORMAL);
        picture.setFlag(PictureVisableStatus.NORMAL);
        try {
            picture.setSize(minIOUtil.getPictureSize(userId,locate));

        } catch (Exception e) {
            e.printStackTrace();
        }
        //5.保存
        save(picture);
        //6.返回图片路径
        return ResultUtil.data(locate);

    }
    @Transactional
    @Override
    public ResultMessage<String> insertPictures(List<MultipartFile> multipartFiles) {
        String token = UserRequest.getCurrentToken();
        log.info("token:"+token);
        AuthUser authUser = tokenUtil.parseToken(token);
        String userId =String.valueOf( authUser.getId());
        //1.判断用户是否登录
        if(userId==null|| StringUtil.isBlank(userId)){
            throw new BadRequestException(OPERATE_FAILED);
        }
        //2.判断是否上传了图片
        if(multipartFiles==null||multipartFiles.size()==0){
            throw  new BadRequestException(REQUEST_PARAM_ILLEGAL);
        }
        String prefix=userId;
      for(int i = 0;i<multipartFiles.size();i++){
          //3.放入minio
          String  locate = minIOUtil.uploadImgFile(userId, prefix, multipartFiles.get(0), null);
          log.info("上传图片到Minio中，图片路径是{}",locate);
          //4.构建图片上传
          Picture picture=new Picture();//创建对象
          picture.setUserId(Long.valueOf(userId));
          picture.setPicturePath(locate);//minio路径
          picture.setIsDelete(PictureDeleteStatus.NORMAL);
          picture.setFlag(PictureVisableStatus.NORMAL);
          try {
              picture.setSize(minIOUtil.getPictureSize(userId,locate));

          } catch (Exception e) {
              e.printStackTrace();
          }
          //5.保存
          save(picture);
      }


        //6.成功
        return ResultUtil.success(ResultCode.SUCCESS);
    }
    @Transactional
    @Override
    public ResultMessage<Object> queryHistoryPicture() {
        String token = UserRequest.getCurrentToken();
        log.info("token:"+token);
        AuthUser authUser = tokenUtil.parseToken(token);
        String userId =String.valueOf( authUser.getId());
        //1.判断用户是否登录
        if(userId==null|| StringUtil.isBlank(userId)){
            throw new BadRequestException(OPERATE_FAILED);
        }
        log.info("查询用户：{}",userId);
        List<Picture>pictures = lambdaQuery().eq(Picture::getUserId,userId)
                .eq(Picture::getIsDelete,PictureDeleteStatus.NORMAL)
                .eq(Picture::getFlag,PictureVisableStatus.NORMAL)
                .list();

        return ResultUtil.data(pictures);
    }
    @Transactional
    @Override
    public ResultMessage<Object> deletePicture(String pictureId) {
        String token = UserRequest.getCurrentToken();
        log.info("token:"+token);
        AuthUser authUser = tokenUtil.parseToken(token);
        String userId =String.valueOf(authUser.getId());
        log.info("deletePicture_userId:{}",userId);
        //1.判断用户是否登录
        if(userId==null|| StringUtil.isBlank(userId)){
            throw new BadRequestException(OPERATE_FAILED);
        }
        //2.更新
        boolean updateResult = lambdaUpdate()
                .eq(Picture::getPictureId, pictureId)
                .set(Picture::getIsDelete, PictureDeleteStatus.FROZEN)
                .update();
        if (updateResult) {
            return ResultUtil.success();
        } else {
            // 如果更新失败，可以根据具体情况返回失败消息或者抛出异常
            throw new BadRequestException(OPERATE_FAILED);
        }
    }


    //删除多张图片
    @Transactional
    @Override
    public ResultMessage<Object> deletePictures(List<String> pictureIds) {
        String token = UserRequest.getCurrentToken();
        log.info("token:"+token);
        AuthUser authUser = tokenUtil.parseToken(token);
        String userId =String.valueOf( authUser.getId());
        //1.判断用户是否登录
        if(userId==null|| StringUtil.isBlank(userId)){
            throw new BadRequestException(OPERATE_FAILED);
        }
        for(String pictureId:pictureIds){
            lambdaUpdate().eq(Picture::getPictureId,pictureId).set(Picture::getIsDelete,PictureDeleteStatus.FROZEN);
        }
        return ResultUtil.success();
    }

    /**
     * AI扩图
     * @return
     */
    @Override
    public ResultMessage<Object> putMakePictureAI() {
        String token = UserRequest.getCurrentToken();
        log.info("token:"+token);
        AuthUser authUser = tokenUtil.parseToken(token);
        String userId =String.valueOf( authUser.getId());
        //1.判断用户是否登录
        if(userId==null|| StringUtil.isBlank(userId)){
            throw new BadRequestException(OPERATE_FAILED);
        }

        String buckerName=userId;
        //3.放入minio
//        String  locate = minIOUtil.uploadImgFile(userId, prefix, multipartFile, null);
        String locate = minIOUtil.upload(buckerName,buckerName,"F:\\truth_seer\\src\\main\\resources\\MakePictureAI.jpg");
        log.info("上传图片到Minio中，图片路径是{}",locate);
        //4.构建图片上传
        Picture picture=new Picture();//创建对象
        picture.setUserId(Long.valueOf(userId));
        picture.setPicturePath(locate);//minio路径
        picture.setIsDelete(PictureDeleteStatus.NORMAL);
        picture.setFlag(PictureVisableStatus.NORMAL);
        try {
            picture.setSize(minIOUtil.getPictureSize(userId,locate));

        } catch (Exception e) {
            e.printStackTrace();
        }
        //5.保存
        save(picture);
        //6.返回图片路径
        return ResultUtil.data(locate);

    }

    /**
     * 一键换天
     * @param typeId
     * @return
     */
    @Override
    public ResultMessage<Object> putMakePictureAir(Integer typeId) {
        String token = UserRequest.getCurrentToken();
        log.info("token:"+token);
        AuthUser authUser = tokenUtil.parseToken(token);
        String userId =String.valueOf( authUser.getId());
        //1.判断用户是否登录
        if(userId==null|| StringUtil.isBlank(userId)){
            throw new BadRequestException(OPERATE_FAILED);
        }

        String buckerName=userId;
        //3.放入minio
//        String  locate = minIOUtil.uploadImgFile(userId, prefix, multipartFile, null);
        String locate =null;
         if(typeId==1){
            locate = minIOUtil.upload(buckerName,buckerName,"F:\\truth_seer\\src\\main\\resources\\Air2.jpg");

        }else
            locate = minIOUtil.upload(buckerName,buckerName,"F:\\truth_seer\\src\\main\\resources\\Air3.jpg");
        log.info("上传图片到Minio中，图片路径是{}",locate);
        //4.构建图片上传
        Picture picture=new Picture();//创建对象
        picture.setUserId(Long.valueOf(userId));
        picture.setPicturePath(locate);//minio路径
        picture.setIsDelete(PictureDeleteStatus.NORMAL);
        picture.setFlag(PictureVisableStatus.NORMAL);
        try {
            picture.setSize(minIOUtil.getPictureSize(userId,locate));

        } catch (Exception e) {
            e.printStackTrace();
        }
        //5.保存
        save(picture);
        //6.返回图片路径
        return ResultUtil.data(locate);
    }

    @Override
    public ResultMessage<Object> putMakeLightingTreatment(Integer typeId) {
        String token = UserRequest.getCurrentToken();
        log.info("token:"+token);
        AuthUser authUser = tokenUtil.parseToken(token);
        String userId =String.valueOf( authUser.getId());
        //1.判断用户是否登录
        if(userId==null|| StringUtil.isBlank(userId)){
            throw new BadRequestException(OPERATE_FAILED);
        }

        String buckerName=userId;
        //3.放入minio
//        String  locate = minIOUtil.uploadImgFile(userId, prefix, multipartFile, null);
        String locate =null;
        if(typeId==1){
            locate = minIOUtil.upload(buckerName,buckerName,"F:\\truth_seer\\src\\main\\resources\\ControllLight1.jpg");
        }else
            locate = minIOUtil.upload(buckerName,buckerName,"F:\\truth_seer\\src\\main\\resources\\ControllLight2.jpg");
        log.info("上传图片到Minio中，图片路径是{}",locate);
        //4.构建图片上传
        Picture picture=new Picture();//创建对象
        picture.setUserId(Long.valueOf(userId));
        picture.setPicturePath(locate);//minio路径
        picture.setIsDelete(PictureDeleteStatus.NORMAL);
        picture.setFlag(PictureVisableStatus.NORMAL);
        try {
            picture.setSize(minIOUtil.getPictureSize(userId,locate));

        } catch (Exception e) {
            e.printStackTrace();
        }
        //5.保存
        save(picture);
        //6.返回图片路径
        return ResultUtil.data(locate);
    }

    /**
     * 画质增强
     * @return
     */

    @Override
    public ResultMessage<Object> putMakeHighDefinition() {
        String token = UserRequest.getCurrentToken();
        log.info("token:"+token);
        AuthUser authUser = tokenUtil.parseToken(token);
        String userId =String.valueOf( authUser.getId());
        //1.判断用户是否登录
        if(userId==null|| StringUtil.isBlank(userId)){
            throw new BadRequestException(OPERATE_FAILED);
        }

        String buckerName=userId;
        String locate =null;
            locate = minIOUtil.upload(buckerName,buckerName,"F:\\truth_seer\\src\\main\\resources\\HighDefinition.jpg");

        //4.构建图片上传
        Picture picture=new Picture();//创建对象
        picture.setUserId(Long.valueOf(userId));
        picture.setPicturePath(locate);//minio路径
        picture.setIsDelete(PictureDeleteStatus.NORMAL);
        picture.setFlag(PictureVisableStatus.NORMAL);
        try {
            picture.setSize(minIOUtil.getPictureSize(userId,locate));

        } catch (Exception e) {
            e.printStackTrace();
        }
        //5.保存
        save(picture);
        //6.返回图片路径
        return ResultUtil.data(locate);
    }

    @Override
    public ResultMessage<Object> getIdCard() {
        return null;
    }
}
